const puppeteer = require('puppeteer');
const devices = require('puppeteer/DeviceDescriptors');
const iPhone = devices['iPhone 6'];
// 休眠函数
function sleep(second) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(' enough sleep~');
        }, second);
    })
}
// 站点地址url
// var url = `https://www.amemv.com/share/user/57774648217?u_code=17deh21jb&timestamp=1536161037&utm_source=qq&utm_campaign=client_share&utm_medium=android&app=aweme&iid=43305155235`
var url = `http://v.douyin.com/dk4pNY/`

class Parse {
  constructor() {
    this.page = null
    this.browser = null
    this.bookMessage = {}
  }
  async init() {
    // 构造浏览器对象
    // 显示浏览器
    console.log(1)
    this.browser = await puppeteer.launch({
      'headless': false,
    });
    // 创建页面
    console.log(2)
    this.page = await this.browser.newPage();
    console.log(3, iPhone)
    // await page.emulate(iPhone)
    console.log(4)
    await this.getBook()
  }
  async getBook() {
    // 打开页面
    console.log('进入getBook')
    await this.page.goto(url);
    let page = await this.page
    // 等待页面请求完成
    page.on('requestfinished', request => {
      // 查看所有请求地址
      console.log(request.url)
      // ajax
      if (request.resourceType == "xhr") {
        // 匹配所需数据的请求地址
        if(request.url.indexOf('/aweme/v1/aweme/post/?user_id=') != -1) {
          (async () => {
            try {
              // 获取数据并转为json格式
              let res = await request.response();
              let result = await res.json();
              let res_data = result.data     
              // 接口数据中找到需要的数据 
              console.log('获取到的数据', res_data)
              this.bookMessage = {                        
                'book_name': res_data.bookName,              
                'book_summary': res_data.desc,              
                'author_name': res_data.authorName,              
              }
              let data = await this.bookMessage
            } catch(err) {
              console.log(err)
            }
          })()
        }
      }
    });
    console.log(111)
  }
}

let parse = new Parse()
parse.init()